package main

import (
	"fmt"
	"github.com/satori/go.uuid"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"mxshop_api/goods_web/global"
	"mxshop_api/goods_web/initialize"
	"mxshop_api/goods_web/utils"
	"mxshop_api/goods_web/utils/register"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	//1.初始化日志
	initialize.InitLogger()
	//2.初始化配置
	initialize.InitConfig()
	//3.初始化路由
	Router := initialize.InitRouter()
	//4.初始化翻译
	if err := initialize.InitTrans("zh"); err != nil {
		zap.S().Panic("初始化翻译失败", err.Error())
	}
	//5.初始化rpc连接
	initialize.InitSrvConn()
	//6.初始化sentinel
	initialize.InitSentinel()

	viper.AutomaticEnv()
	//如果是本地开发环境端口号固定，生产环境则动态获取
	debug := viper.GetBool("MXSHOP_DEBUG")
	zap.S().Debug("debug:", debug)
	if !debug {
		port, err := utils.GetFreePort()
		if err == nil {
			global.WebConfig.Port = port
		}
	}

	//服务注册
	client := register.NewConsul(global.WebConfig.Consul.Host, global.WebConfig.Consul.Port)
	serviceId := fmt.Sprintf("%s", uuid.NewV4())
	err := client.Register(global.WebConfig.Host, global.WebConfig.Port, global.WebConfig.Name, global.WebConfig.Tags, serviceId)
	if err != nil {
		zap.S().Panic("服务注册失败：", err.Error())
	}

	zap.S().Debugf("启动服务器:%s:%d", global.WebConfig.Host, global.WebConfig.Port)
	if err := Router.Run(fmt.Sprintf(":%d", global.WebConfig.Port)); err != nil {
		zap.S().Panic("启动失败", err.Error())
	}

	//接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = client.DeRegister(serviceId); err != nil {
		zap.S().Info("注销失败")
	}
	zap.S().Info("注销成功")

}
